package com.leetcode.LC_MED;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;

public class LC692 {
    public List<String> topKFrequent(String[] words, int k) {
        HashMap<String, Integer> map = new HashMap<>();

        for (String word : words) {
            map.put(word, map.getOrDefault(word, 0) + 1);
        }

        PriorityQueue<String> queue = new PriorityQueue<>((o1, o2) -> {
            Integer o1Int = map.get(o1);
            Integer o2Int = map.get(o2);
            if (o1Int.equals(o2Int)) {
                return o2.compareTo(o1);
            } else {
                return o1Int - o2Int;
            }
        });

        for (String s : map.keySet()) {
            queue.offer(s);
            if (queue.size() > k) {
                queue.poll();
            }
        }
        LinkedList<String> stack = new LinkedList<>();
        while (!queue.isEmpty()) {
            stack.push(queue.poll());
        }
        return stack;
    }
}
